#include "mychart.h"
#include "ui_mychart.h"

MyChart::MyChart(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyChart)
{
    ui->setupUi(this);
    initVariable();
    initWindowUI();
    initSignalAndSlot();
}

MyChart::~MyChart()
{
    delete ui;
}
void MyChart::initWindowUI()
{
    chart->setTheme(QChart::ChartThemeHighContrast);//设置chart主题风格
    chartView->setRubberBand(QChartView::RectangleRubberBand);
    chart->addSeries(series);
    // 初始化chart
    series->setUseOpenGL(true);
    //qDebug()<<"OpenGL加速："<<series->useOpenGL();
    chart->legend()->hide();
    chart->setTitle("MyChart");
    chart->setTitleFont(QFont("Times", 20, QFont::Bold));//设置chart标题字体
    chart->setAnimationOptions(QChart::AllAnimations); //启动网格动画
    axisX->setTitleText("v/div");//设置X轴单位
    axisX->setTickCount(12);//设置X轴网格线的数量
    axisX->setLabelsVisible(false);//隐藏X轴的单位
    axisY->setTickCount(13);
    axisY->setTitleText("ms/div");
    axisX->setRange(0,300);//设置X轴最大值与最小值
    axisY->setRange(-1.2,1.2);//设置Y轴最大最小值
    axisX->setMinorTickCount(1);
    // 设置无网格线的颜色与线条类型
    QPen pen;
    pen.setStyle(Qt::SolidLine);
    pen.setBrush(Qt::darkGreen);
    pen.setWidth(2);
    axisX->setGridLinePen(pen);
    axisY->setGridLinePen(pen);
    // 添加网格线到chart中
    chart->setAxisX(axisX,series);
    chart->setAxisY(axisY,series);
    // 将chart添加到layout中
    QVBoxLayout *layout = ui->LayoutMyChart;
    layout->addWidget(chartView);
    // 设置显示波形线条颜色
    this->series->setColor(Qt::black);

}
void MyChart::initVariable()
{
    chart = new QChart();
    series = new QLineSeries();
    axisX = new QValueAxis();
    axisY = new QValueAxis();
    chartView = new QChartView(chart);
    data = new MyData();
    timer = new QTimer(this);
    //设置timer刷新时间为500ms
    timer->start(500);
}
void MyChart::initSignalAndSlot()
{
    connect(this->timer,SIGNAL(timeout()),this,SLOT(slotDealWithTimeout()));
    connect(this->ui->btResetChart,SIGNAL(clicked()),this,SLOT(slotDealWithPreesResetChart()));
    connect(this->ui->btStopChart,SIGNAL(clicked()),this,SLOT(slotDealWithPressStopChart()));
    connect(this->ui->btRunChart,SIGNAL(clicked()),this,SLOT(slotDealWithPressRunChart()));
}



void MyChart::showData(unsigned int cout ,double* value)
{
    QVector<QPointF> points;
    for(unsigned int i = 0; i < cout; i++){
        points.append(QPointF(i,value[i]));
    }
    series->replace(points);
}

void MyChart::slotDealWithTimeout()
{
    //TOD0: 处理函数将函数波形显示到chart中
    this->data->reFreshData();//先更新一次数据
    showData(this->data->getCount(),this->data->getValue());

}
void MyChart::slotDealWithPreesResetChart()
{
    //TODO:重置波形的显示X，Y轴
    axisX->setRange(0,300);//设置X轴最大值与最小值
    axisY->setRange(-1.2,1.2);//设置Y轴最大最小值
}
void MyChart::slotDealWithPressRunChart()
{
    //TODO:继续获取数据,刷新波形
    this->timer->start(500);
}
void MyChart::slotDealWithPressStopChart()
{
    //TODO:暂停数据的获取和刷新
    this->timer->stop();
}
